﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 凯旋归来管理端.models
{
    class RET
    {
        public string revcode;
        public object revdata;
    }
    class Basic
    {
        public string GetByteString(ref string s, int len, bool debug)
        {
            string msg;
            byte[] buff;
            //名称1
            if (StrToHex(s, 0, s.Length, out buff, out msg) == false)
            {
                s = "";
                return "";
            }
            string ret = Hex2Str(buff, 0, len, false);
            if (debug == false)
            {
                s = Hex2Str(buff, len, buff.Length - len, true);
            }
            return ret;
        }
        public static bool StrToHex(string str, int start, int size, out byte[] ret, out string msg)
        {
            msg = "";
            int i0;
            str = str.Replace(" ", "");
            ret = new byte[str.Length / 2];
            for (i0 = 0; i0 < str.Length / 2; i0++)
            {
                try
                {
                    ret[i0] = Convert.ToByte(str.Substring(i0 * 2, 2), 16);
                }
                catch (Exception ex)
                {
                    msg += ex.Message;
                    return false;
                }
            }
            return true;
        }
        public static string Hex2Str(byte[] by, int start, int size, bool speace)
        {
            StringBuilder ret = new StringBuilder();
            if (size == -1)
            {
                size = by.Length;
            }
            for (int i = 0; i < size; i++)
            {
                ret.Append(by[i + start].ToString("X2"));
                if (speace == true) ret.Append(" ");
            }
            return ret.ToString();
        }
        public static RET GetString(ref string s,bool debug)
        {
            RET retvalue = new RET();
            string msg;
            byte[] buff;
            //名称1
            if (StrToHex(s, 0, s.Length, out buff, out msg) == false)
            {
                retvalue.revcode = msg;
                return retvalue;
            }
            int len = buff[0] + (buff[1] << 8) + (buff[2] << 16) + (buff[3] << 24);
            string ret = "";
            if (len > 0)
            {
                if (len > buff.Length)
                {
                    retvalue.revcode = "数据长度不够!";
                    return retvalue;

                }
                ret = System.Text.Encoding.Default.GetString(buff, 4, len - 1);
            }
            len += 4;
            if (debug == false)
            {
                s = Hex2Str(buff, len, buff.Length - len, true);
            }
            retvalue.revdata = ret;
            return retvalue;
        }
    }
}
